<template>

  <div>
    <div>
      <label class="font">
      <el-button  type="text" icon="el-icon-back" @click="handleBack()" class="fontBack"
          style="color: black;">返回</el-button>
      </label>
      <label style="margin: 5px;">
        |
      </label>
      <label v-if="Type === 'Add'" class="font">
        添加歌曲
      </label>
      <label v-if="Type === 'Update'" class="font">
        修改歌曲
      </label>
    </div>
    <div class="container">

      <div style="margin-left: 30px;">

        <el-form ref="form" :model="form" :rules="rules" label-width="80px" class="form">
          <el-form-item label="歌曲名称" prop="name">
            <el-input v-model="form.name"></el-input>
          </el-form-item>

          <el-form-item label="专辑" prop="album">
            <el-input v-model="form.album"></el-input>
          </el-form-item>

          <el-form-item label="歌词" prop="lyric">
            <el-input type="textarea" v-model="form.lyric" resize="none" :rows="20"></el-input>
          </el-form-item>

          <div>
            <el-upload :action="upload()" :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess">
              <el-button type="primary">添加图片</el-button>
            </el-upload>
            <div class="block">
              <el-image :src="imageUrl" style="width: 300px; height: 200px;"></el-image>
            </div>
          </div>

          <el-upload class="upload-music" ref="upload" :action="uploadMusic()" :on-preview="handlePreview"
            :on-success="handleSuccess" :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
            <div slot="tip" class="el-upload__tip">只能上传MP3文件,且不超过10mb</div>
          </el-upload>
          
        </el-form>
      </div>
      <el-button v-if="Type === 'Add'" type="primary" icon="el-icon-check" class="but"
        @click="handleAdd('form')">添加</el-button>
      <el-button v-if="Type === 'Update'" type="primary" icon="el-icon-check" class="but"
        @click="handleUpdate('form')">修改</el-button>
    </div>
  </div>
</template>

<script>


import { addSong, UpdateById, SelectSongById } from '@/api/song'

export default {
 

  data() {

    return {
      Type: '',
      SongUrl: '',
      imageUrl: 'https://web-photoss.oss-cn-beijing.aliyuncs.com/72235142-2f0d-4662-92e1-cc38dbacb5ea.jpg',
      musictotaltimemode:0,
      musictotaltime:'',
      form: {
        name: '',
        album: '',
        lyric: '',
      },
      rules: {
        name: [
          { required: true, message: '请输入歌词', trigger: 'blur' },
        ],
        album: [
          { required: true, message: '请输入专辑', trigger: 'blur' }
        ],
        lyric: [
          { required: true, message: '请输入歌词', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.Type = this.$route.query.type === 'Update' ? 'Update' : 'Add'
    if (this.Type === 'Update') {
      SelectSongById(this.$route.query.id).then((res) => {
        if (res.data.code === 1) {
          this.form = res.data.data
          this.imageUrl = res.data.data.image
          this.SongUrl = res.data.data.url
        }
      })
    }
  },
  methods: {
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleSuccess(res, file) {
      if (res.code === 1) {
        this.SongUrl = res.data
        const audio = new Audio(this.SongUrl)
            audio.load()
            audio.oncanplay = () => {
                let total = parseInt(audio.duration)
                this.musictotaltimemode= total
                let minute=total % 60
                let seconds=(total-minute)/60
                if(minute>=0 && minute <10 ){
                  minute = '0'+minute;
                }
                this.musictotaltime= seconds +':' + minute
            }
        this.$message.success('添加成功')
      }
    },
    handlePreview(file) {
      const isMp3 = file.type === 'mp3';
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isMp3) {
        this.$message.error('上传音乐只能是mp3格式!');
      }
      if (!isLt10M) {
        this.$message.error('上传音乐文件不能超过 10MB!');
      }
      return isMp3 && isLt10M;
    },
    handleBack() {
      this.$router.push({
        path: `/ManagerSong?id=${this.$route.query.singerId}`,     
      })
    },
    handleBackUpdate() {
      this.$router.push({
        path: `/ManagerSong?id=${this.$route.query.singerId}`,
      })
    },
    upload() {
      return '/api/admin/common/upload'
    },
    uploadMusic() {
      return '/api/admin/common/uploadMusic'
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = `${res.data}`;
      
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    handleAdd(form) {

      //进行表单验证
      this.$refs[form].validate((valid) => {
        if (valid) {
          const data = { "name": this.form.name, "album": this.form.album, "lyric": this.form.lyric, "image": this.imageUrl, "singerId": this.$route.query.singerId, "url": this.SongUrl ,"musictotaltime" :this.musictotaltime}
          addSong(data).then((res) => {
            if (res.data.code === 1) {
              this.$message.success('添加成功')
              this.handleBack()
            }
            else {
              this.$message.error(res.data.msg)
            }
          })
        } else {
          this.$message.error('请输入正确的表单项')
        }
      })
    },
    handleUpdate(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          const data = { "name": this.form.name, "album": this.form.album, "lyric": this.form.lyric, "image": this.imageUrl, "id": this.$route.query.id, "url": this.SongUrl ,"musictotaltime" :this.musictotaltime}
          UpdateById(data).then((res) => {
            if (res.data.code === 1) {
              this.$message.success('修改成功')
              this.handleBackUpdate()
            } else {
              this.$message.error(res.data.msg)
            }
          })
        } else {
          this.$message.error('请输入正确的表单项')
        }
      })
    }
  }
}



</script>

<style scoped>
.container {
  position: relative;
  z-index: 1;
  height: 1000px;
  background: #fff;
  padding: 50px;
  border-radius: 4px;
  margin-top: 10px;
  width: 900px;
  margin: auto;
}

.font {
  font-size: 15px;
  font-weight: bolder;
}

.fontBack {
  font-size: 15px;
  font-weight: normal;
}

.img {
  margin-left: 400px;
  margin-bottom: 500px;
  width: 100px;
  left: 50%;
}

.block {
  margin-top: 10px;

}

.form {
  margin-left: 10%;
  width: 50%;
}

.but {
  margin-top: 50px;
  float: right;
  width: 100px;
}
</style>